<?php

namespace app\common\service;

use app\common\traits\JumpTrait;
use think\facade\Db;
use think\exception\ValidateException;
class BaseService
{
    /**
     * 成功返回数据
     * @param string $message
     * @param array $data
     * @param int $code
     * @return array
     */
    public static function success($message = '', $data = [], $code = 200)

    {
        return ['code' => $code, 'data' => $data, 'message' => $message];
    }
    /**
     * 失败返回数据
     * @param string $message
     * @param array $data
     * @param int $cod0e
     * @return array
     */
    public static function fail($message = '', $data = [], $code = 400)
    {
        return ['code' => $code, 'data' => $data, 'message' => $message];
    }

    /**
     * Author:Yingbo Sun
     * 开启事务
     */
    public static function beginTrans()
    {
        Db::startTrans();
    }

    /**
     * Author:Yingbo Sun
     * 提交事务
     */
    public static function commitTrans()
    {
        Db::commit();
    }

    /**
     * Author:Yingbo Sun
     * 关闭事务
     */
    public static function rollbackTrans()
    {
        Db::rollback();
    }

    /**
     * 校验是否为空 和设置
     * Author:William
     * @param $params 注入参数
     * @return array
     */
    public static function checkPamasNull($params)
    {
        if (empty($params) && isset($params)) {
            return self::fail();
        } else {
            return self::success('成功', $params);
        }
    }

    /**
     * validate验证器验证
     * @param array|string $params
     * @return array|string|true|void
     */
    public static function validateFail($obj, $params)
    {
        //验证参数
        try {
            validate($obj)->batch(true)->check($params);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息
            $msg = implode(',', $e->getError());
            return self::fail("$msg");
        }
    }


}